# -*- encoding=UTF-8 -*-
__author__ = "zichuanlu"

import os

import xlrd
import xlwt
from xlutils.copy import copy


class myTool(object):

    @classmethod
    def repeat(cls, times):
        """
        重复执行函数
        """

        def repeat_helper(f):
            def call_helper(*args):
                for i in range(0, times):
                    f(*args)

            return call_helper

        return repeat_helper

    @classmethod
    def write_excel_xls_append(cls, filepath, data):
        """
        追加写入excel
        :param filepath:
        :param data:
        :return:
        """

        workbook = xlrd.open_workbook(filepath)
        worksheet = workbook.sheet_by_name("sheet1")
        rows_old = worksheet.nrows

        new_workbook = copy(workbook)
        new_worksheet = new_workbook.get_sheet(0)  # 获取转化后工作簿中的第一个表格

        if rows_old != 0:
            for i in range(0, len(data)):
                new_worksheet.write(rows_old, i, data[i])
        else:
            # 首次写入标题
            new_worksheet.write(0, 0, "测试时间")
            new_worksheet.write(0, 1, "测试序号")
            new_worksheet.write(0, 2, "耗时")

        new_workbook.save(filepath)

    @classmethod
    def create_xlsx(cls, filepath):
        """
        创建excel文件，不存在才创建
        :param filepath:
        :return:
        """
        if not os.path.exists(filepath):
            workbook = xlwt.Workbook(encoding='utf-8')
            sheet = workbook.add_sheet('sheet1')
            workbook.save(filepath)

